package com.example.book.service.impl.user;

import com.example.book.context.BaseContext;
import com.example.book.dto.BookDTO;
import com.example.book.dto.BorrowDTO;
import com.example.book.dto.BorrowPageDTO;
import com.example.book.dto.UserDTO;
import com.example.book.entity.Book;
import com.example.book.entity.Borrow;
import com.example.book.entity.User;
import com.example.book.mapper.BookMapper;
import com.example.book.mapper.BorrowMapper;
import com.example.book.mapper.UserMapper;
import com.example.book.result.PageResult;
import com.example.book.vo.BorrowVO;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import javax.security.auth.login.AccountNotFoundException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl implements UserService{
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private BookMapper bookMapper;
    @Autowired
    private BorrowMapper borrowMapper;
    //用户登录
    @Override
    @Transactional
    public void login(UserDTO userDTO) throws AccountNotFoundException {
        String name = userDTO.getName();
        String password = userDTO.getPassword();
        User user = userMapper.getUserMeg(name);
        if(user==null){
            //账号不存在的时候
            throw new AccountNotFoundException("账号不存在");
        }
        //md5加密
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if(!password.equals(user.getPassword())){
            //密码错误
            throw new AccountNotFoundException("密码错误");
        }
    }
    //用户注册
    @Override
    @Transactional
    public void insert(User user) throws AccountNotFoundException {
        //md5加密
        String password = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        user.setPassword(password);
        User user1 = (userMapper.getUserMeg(user.getName()));
        if(user1==null){
            userMapper.insert(user);
        }else throw new AccountNotFoundException("账号已存在");
    }
    //借阅图书
    @Override
    @Transactional
    public void borrowByBookName(List<String> bookName) throws AccountNotFoundException {
        List<Integer> categoryList = bookMapper.getBookMegByBookName(bookName);
        //TODO  使用stream()方法获取集合的流（豪用）
        List<Borrow> borrows = bookName.stream()
                .map(name -> {
                    Borrow borrow = new Borrow();
                    borrow.setBookName(name);
                    //TODO 后面安排线程 borrow.setUserName(BaseContext.getCurrentName());
                    borrow.setUserName(BaseContext.getCurrentName());
                    borrow.setCreateTime(LocalDateTime.now());
                    borrow.setUpdateTime(LocalDateTime.now());
                    return borrow;
                }).collect(Collectors.toList());
        for (int i = 0; i < categoryList.size(); i++) {
            borrows.get(i).setCategoryId(categoryList.get(i));
        }
        //查找是否有未归还的书籍又一次被借阅
        List<Borrow> borrows1 = borrowMapper.getMegByName(borrows);
        //若没有重复借的书则进行插入
        if(borrows1.size()==0){
            borrowMapper.insertBook(borrows);
            //将book数据库中书的数量减一
            bookMapper.updateBookNumberMeg(borrows);
        }else throw new AccountNotFoundException("存在已借过的书籍");
    }
    //显示用户借阅的图书
    @Override
    public PageResult borrowBook(BorrowPageDTO borrowPageDTO) {
        PageHelper.startPage(borrowPageDTO.getPage(), borrowPageDTO.getPageSize());//获取页数和记录数
        //TODO 使用BaseContext.getCurrentName();获取用户名。
        borrowPageDTO.setUserName(BaseContext.getCurrentName());
        Page<BorrowVO> page = borrowMapper.getBookPage(borrowPageDTO);//获取借阅的图书信息
        long total = page.getTotal();//获取总记录数
        List<BorrowVO> borrowVOS = page.getResult();//获取记录数的集合
        PageResult pageResult = new PageResult(total,borrowVOS);//将集合放入pageResult实体类中
        return pageResult;
    }
    //图书的归还
    @Override
    @Transactional
    public void giveBook(List<String> bookName) {
        List<BorrowDTO> borrowDTOS = bookName.stream()
                .map(name -> {
                    BorrowDTO borrowDTO = new BorrowDTO();
                    borrowDTO.setBookName(name);
                    //TODO 后面安排线程 borrowDTO.setUserName(BaseContext.getCurrentName());
                    borrowDTO.setUserName(BaseContext.getCurrentName());
                    return borrowDTO;
                }).collect(Collectors.toList());
        //删除borrow库中的借阅信息
        borrowMapper.deleteBorrowMeg(borrowDTOS);
        //将book库中的书籍数量加一
        for (String name:bookName) {
            bookMapper.updateBookMegByBorrow(name);
        }
    }
}
